<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <title>jQT Mail</title>
        <style type="text/css" media="screen">@import "../../themes/css/vanilla.css";</style>
        <style type="text/css" media="screen">
            .edgetoedge li a .preview, .edgetoedge li a .subject {
                display: block;
                color: #999;
                font-size: 12px;
                font-weight: normal;
            }
            .edgetoedge li a .subject {
                color: #000;
                font-size: 14px;
            }
        </style>
        <script src="../../../../www/cordova-1.5.0.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../src/lib/zepto.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../src/jqtouch.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../html/js/server.js" type="text/javascript" charset="utf-8"></script>
        
        <script type="text/javascript" charset="utf-8">
            var jqtouch = $.jQTouch({
                icon: "mail.png",
                preloadImages: [
                    'themes/jqt/img/chevron.png',
                    'themes/jqt/img/back_button.png',
                    'themes/jqt/img/back_button_clicked.png',
                    'themes/jqt/img/button_clicked.png',
                    'themes/jqt/img/grayButton.png',
                    'themes/jqt/img/whiteButton.png'
                ]
            });
            // Add an onload function
            /*
            $(function(){
                // Dynamically set next page titles after clicking certain links
                $('#home ul a, #mailbox ul a').click(function(){
                    $( $(this).attr('href') + ' h1' ).html($(this).html());
                });
            });
            */
  
        </script>
        
        <script>	
		// Do not forget to put javascript in own defined js file
		
		// This function checks for all added files and images and will send them
		// to database. If connection fails (offline) stores in local storage.
		
		/* Declaration of object.
		*  Following variables will be assigned: latitude and langtitude
		*/
		
		function Geo(){
			this.lat = "";
			this.lon = "";
			this.getLat = function(){ return this.lat; };
			this.getLon = function(){ return this.lon; };
			this.setLoc = function(lat, lon) {this.lat = lat; this.lon = lon;};
		}
		
		var geo = new Geo();
		
		document.addEventListener("deviceready", onDeviceReady, false);

	    // Cordova is ready
	    //
	    
	    var f;
	    
	   function onDeviceReady() {
		   //uploadTest(); // function of server.js should output message.
		   if(localStorage.ReportText){
			   document.getElementById("report").value = localStorage.ReportText;
		   }
		   navigator.geolocation.getCurrentPosition(onSuccess, onError);
	       pictureSource=navigator.camera.PictureSourceType;
	       destinationType=navigator.camera.DestinationType;
        
	    }

	    // onSuccess Geolocation
	    //
	    function onSuccess(position) {
	    	geo.setLoc(position.coords.latitude, position.coords.longitude);
	        var element = document.getElementById('geolocation');
	        element.innerHTML = 'Geolocation: '+ geo.getLat() + '-' + geo.getLon();
	        
	        console.log(		'Altitude: '           + position.coords.altitude              + '<br />' +
	                            'Accuracy: '           + position.coords.accuracy              + '<br />' +
	                            'Altitude Accuracy: '  + position.coords.altitudeAccuracy      + '<br />' +
	                            'Heading: '            + position.coords.heading               + '<br />' +
	                            'Speed: '              + position.coords.speed                 + '<br />' +
	                            'Timestamp: '          + position.timestamp          + '<br />');
	    }

	    // onError Callback receives a PositionError object
	    //
	    function onError(error) {
	        alert('code: '    + error.code    + '\n' +
	                'message: ' + error.message + '\n');
	    }
	   
	   function prepareFile(fileSystem) {
			
			f = fileSystem;
			fileSystem.root.getDirectory("Nature", {create: true, exclusive: false}, gotFS, fail);
		    
		}

	
	   function gotFS(fileSystem) {
		   //maybe html is better for the file in order toget more structural file
		   
	       f.root.getFile("Nature/nature.txt", {create: true, exclusive: false}, gotFileEntry, fail);
	       
		   
	    }

	    function gotFileEntry(fw) {
			
	    	fw.createWriter(function(writerOb) {
				writerOb.onwrite=function() {
					document.getElementById("report").value = "";
					localStorage.removeItem("Reporttext");
					alert("The written report is successfully saved");
					uploadFile(fw.fullPath);
				}
			//go to the end of the file...
			writerOb.seek(writerOb.length);
			writerOb.write(new Date().toString() +'\nGeolocation: '+ geo.getLat() + '-' + geo.getLon()+ ":\n " +localStorage.Reporttext);
			
			});
	    }

	    function fail(error) {
	        console.log(error.code);
	    }

    
	var Allimages = new Array();
	var i=0;
    // Called when a photo is successfully retrieved
    //
    function onPhotoDataSuccess(imageURI) {
      // Uncomment to view the base64 encoded image data
       console.log(imageURI);

      // Get image handle
      //
      Allimages[i++] = imageURI;
      var images = document.getElementById("ImageList");
      var list = document.createElement('li');
      list.innerHTML = imageURI;;
      images.appendChild(list); 
      uploadPhoto(imageURI);
    }
	
   
    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI 
      // console.log(imageURI);

      // Get image handle
      //
      //var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      //largeImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      //largeImage.src = imageURI;
      Allimages[i++] = imageURI;
      var images = document.getElementById("ImageList");
      var list = document.createElement('li');
      list.innerHTML = imageURI;;
      images.appendChild(list);
      uploadPhoto(imageURI);
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI });
     
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function getPhoto(source) {
    	// Retrieve image file location from specified source
    	  navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 40, 
    	    destinationType: destinationType.FILE_URI,
    	    sourceType: pictureSource.SAVEDPHOTOALBUM });
    }

    // Called if something bad happens.
    // 
    function onFail(message) {
      alert('Failed because: ' + message);
    }
    
		function sendReport(){
			var text = document.getElementById('report').value;
			
			/* This functions intiates DropBox.java class and sends text to write to file and
			*  to synchronize it with the latest changes. 
			*/
			syncronize(text);
			
			if( text != ""){
				window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, prepareFile, fail);
			}
			
			document.getElementById('geolocation').innerHTML = "";
			alert("All files have been sent successfully");
			// check for local storage
			// connect to a server
			// send files
		}
		
		function readReport(){
			// connect to server
			// check if new data are available
			// synchronise
			// list all data
			// make available to read and see images
		}
		
		function readNotes(){
			// connect to server
			// check if new data are available
			// synchronise
			// possibility to read and write new notes
			// ! if time possibility check out functionality for done todo list notes.
		}
		
		function addPhoto(){
			var choices = "Take a picture, Browse, Cancel";
			navigator.notification.confirm(
		            "Please make a choice",  // message
		            Choice,              		 // callback to invoke with index of button pressed
		            "Image",            	 // title
		            choices          		 // buttonLabels
		    );
		}

		function Choice(button){
			if(button==1){
				capturePhoto();
			}
			else if(button==2){
				getPhoto();
			}
			else
				return false;
		}

		
		function addFile(){
			alert("I am gonna add file");
			// browse functio ?!
		}
		
		function textOnChange(){
			localStorage.Reporttext = document.getElementById("report").value;
			console.log("Local Storage output for textarea: "+localStorage.Reporttext);
		}
		
		</script>
    </head>
    <body>
        <div id="jqt">
        	<div id="Send" class="current">
                <div class="toolbar">
                    <h1>Report</h1>
                    <a class="button slideup" id="notesButton" href="#About">About</a>
                </div>
                
                <ul class="individual">
                	<li><a rel="external" href="Map.html">Map</li>
                    <li><a href="#Read">Read</a></li>
                    <li><a href="#Notes">Notes</a></li>
                    <li><a href="#OAuth">OAuth</a></li>
                </ul>
                
                <form>
                
                <ul>
                	<li id="geolocation"></li>
					<li><textarea id="report" placeholder="Textarea" onchange="javascript:textOnChange();"></textarea></li>
				</ul>
				</form>
				
				<ul id="ImageList"></ul>
				<div style="margin: 10px;">
					<a href="javascript:addPhoto();" class="whiteButton">+Add photo</a>
                    <a href="javascript:addFile();" class="whiteButton">+Add file</a>
                    <!-- <a href="javascript:showIt('Something interesting');" class="whiteButton">Send message</a>  -->
                    <br />
                    <a href="javascript:sendReport();" class="greenButton">Submit</a>
                </div>
			
                
        	</div>
			
			<div id="Read" class="selectable">
				<div class="toolbar">
                    <h1>Read</h1>
                    <a class="back" href="#Send">Back</a>
                </div>
                <p>You are in Read</p>
           		
				
			</div>
			
			<div id="Notes" class="selectable">
			<div class="toolbar">
                    <h1>Notes</h1>
                    <a class="back" href="#Send">Back</a>
                </div>
				<p>You are in Notes<p>
				
			</div>
			
			<div id="About" class="selectable">
				<h1>About</h1>
                  <p><img src="mail.png" /></p>
                    <p><strong>Nature</strong><br />Version 1.0 beta<br />
                        <a href="http://www.hig.no">By Adiljan and Olav</a></p>
                    <p><em>This project is developed by Adiljan Abdurihim and Olav Brenna Hansen for the "Recent Advances in Web Technology" course, 12HMACS.</em></p>
                    
                    <p><br /><br /><a href="#" class="whiteButton goback">Close</a></p>
				
			</div>
			
			<div id="OAuth" class="selectable">
				<h1>OAuth</h1>
                  <p><img src="mail.png" /></p>
                    <p><strong>Nature</strong><br />Version 1.0 beta<br />
                        <a rel="external" href="../oauth/oauth.html">oauth authentication</a></p>
                    <p><em>This project is developed by Adiljan Abdurihim and Olav Brenna Hansen for the "Recent Advances in Web Technology" course, 12HMACS.</em></p>
                    
                    <p><br /><br /><a href="#" class="whiteButton goback">Close</a></p>
				
			</div>		
		</div>
	</body>
</html>

